package hackathon.att.atl.android.autoresponder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import hackathon.att.atl.android.autoresponder.SendMessage;

public class IncomingCallBroadcastReceiver extends BroadcastReceiver {
	
	private static String lastKnownPhoneState = null;
	AutoResponderDAO dao;
	
    public IncomingCallBroadcastReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
//        throw new UnsupportedOperationException("Not yet implemented");
    	// not sure if we need this one
    	boolean callAnswered = false;
    	boolean callMissed = false;
    	String phoneNumber=null;
    	if(intent != null && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED))
    	{
            //State has changed
            String newPhoneState = intent.hasExtra(TelephonyManager.EXTRA_STATE) ? intent.getStringExtra(TelephonyManager.EXTRA_STATE) : null;
            //See if the new state is 'ringing'
            if(newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            	phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            }
            else if (newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
            {
            	callAnswered = true;
            }
//            else if (newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_IDLE))
//            {
//            	// Phone is not ringing and not off the hook
//            }
            else if(lastKnownPhoneState != null && lastKnownPhoneState.equals(TelephonyManager.EXTRA_STATE_RINGING) && 
            		newPhoneState.equals(TelephonyManager.CALL_STATE_IDLE)) {
            	// if the last know state was ringing and now its idle that means we missed the call ... right??
            	callMissed = true;
            }
            	 
            lastKnownPhoneState = newPhoneState;
    	}
    	
    	if (callMissed)
    	{
    		// open database
            AutoResponderDAO dao = new AutoResponderDAO(context);
            dao.open();
            
            // Get contact info by phone number
            if (phoneNumber != null && !"".equals(phoneNumber))
            {
            	AutoResponderData data = dao.getContactInfoByPhoneNumber(phoneNumber);
            	
        		SendMessage sendMessage = new SendMessage();
        		sendMessage.sendMessage(context, (int)data.getId());            	
            }
    	}
    }
}
